<template>
  <div>
    <wd-popup v-model="userDialog.visible" :title="userDialog.title" position="center" closable>
      <wd-row :gutter="20">
        <wd-col :span="18">
          <div v-show="showSearch" class="mb-[10px]">
            <wd-card>
              <view class="search-form">
                <wd-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @confirm="handleQuery" />
                <wd-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @confirm="handleQuery" />
                <wd-button type="primary" @click="handleQuery">搜索</wd-button>
                <wd-button @click="resetQuery">重置</wd-button>
              </view>
            </wd-card>
          </div>

          <wd-card>
            <view v-if="prop.multiple" class="selected-users">
              <wd-tag v-for="user in selectUserList" :key="user.userId" closable @close="handleCloseTag(user)">
                {{ user.nickName }}
              </wd-tag>
            </view>

            <w-table
              ref="tableRef"
              :data="userList"
              :loading="loading"
              :checkbox="prop.multiple"
              @selection-change="handleCheckboxChange"
            >
              <w-table-col prop="userId" label="用户编号" align="center" />
              <w-table-col prop="userName" label="用户名称" align="center" />
              <w-table-col prop="nickName" label="用户昵称" align="center" />
              <w-table-col prop="deptName" label="部门" align="center" />
              <w-table-col prop="phonenumber" label="手机号码" align="center" width="120" />
              <w-table-col prop="createTime" label="创建时间" align="center" width="160" />
            </w-table>

            <wd-pagination
              v-show="total > 0"
              v-model="queryParams.pageNum"
              :page-size="queryParams.pageSize"
              :total="total"
              @change="pageList"
            />
          </wd-card>
        </wd-col>
      </wd-row>

      <template #footer>
        <wd-button @click="close">取消</wd-button>
        <wd-button type="primary" @click="confirm">确定</wd-button>
      </template>
    </wd-popup>
  </div>
</template>

<script setup lang="ts">
import { listUser, optionSelect } from '@/api/system/user';
import type { UserQuery, UserVO } from '@/api/system/user/types';
import useDialog from '@/hooks/useDialog';
import { watchEffect, getCurrentInstance, type ComponentInternalInstance, toRefs, computed, watch, ref, nextTick } from 'vue';

interface PropType {
  modelValue?: UserVO[] | UserVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[] | undefined;
  userIds?: string | number | (string | number)[] | undefined;
}
const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined,
  userIds: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);


const userList = ref<UserVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const selectUserList = ref<UserVO[]>([]);

const queryFormRef = ref<any>();
const tableRef = ref<any>();

const userDialog = useDialog({
  title: '用户选择'
});

const queryParams = ref<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: '',
  deptId: '',
  roleId: '',
  userIds: ''
});

const defaultSelectUserIds = computed(() => computedIds(prop.data));


const confirm = () => {
  emit('update:modelValue', selectUserList.value);
  emit('confirmCallBack', selectUserList.value);
  userDialog.closeDialog();
};

const computedIds = (data: any) => {
  if (data instanceof Array) {
    return data.map((item) => String(item));
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [data];
  } else {
    console.warn('<UserSelect> The data type of data should be array or string or number, but I received other');
    return [];
  }
};

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};


/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.userIds = prop.userIds ? String(prop.userIds) : '';
  const res = await listUser();
  loading.value = false;
  userList.value = res.rows;
  total.value = res.total;
};

const pageList = async () => {
  await getList();
  const users = userList.value.filter((item) => {
    return selectUserList.value.some((user) => user.userId === item.userId);
  });
  await tableRef.value.setCheckboxRow(users, true);
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id;
  handleQuery();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectUserList.value, false);
    selectUserList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectUserList.value.push(row);
  } else {
    selectUserList.value = selectUserList.value.filter((item) => {
      return item.userId !== row.userId;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = userList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectUserList.value.some((item) => item.userId === row.userId)) {
        selectUserList.value.push(row);
      }
    });
  } else {
    selectUserList.value = selectUserList.value.filter((item) => {
      return !rows.some((row) => row.userId === item.userId);
    });
  }
};

const handleCloseTag = (user: UserVO) => {
  const userId = user.userId;
  // 使用split删除用户
  const index = selectUserList.value.findIndex((item) => item.userId === userId);
  const rows = selectUserList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectUserList.value.splice(index, 1);
};

const initSelectUser = async () => {
  if (defaultSelectUserIds.value.length > 0) {
    const { data } = await optionSelect(defaultSelectUserIds.value);
    selectUserList.value = data;
    const users = userList.value.filter((item) => {
      return defaultSelectUserIds.value.includes(String(item.userId));
    });
    await nextTick(() => {
      tableRef.value.setCheckboxRow(users, true);
    });
  }
};
const close = () => {
  userDialog.closeDialog();
};

watch(
  () => userDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      await initSelectUser();
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectUserList.value = [];
    }
  }
);

defineExpose({
  open: userDialog.openDialog,
  close: userDialog.closeDialog
});
</script>

<style lang="scss" scoped>
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.selected-users {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.mb-\[10px\] {
  margin-bottom: 10px;
}

.mt-2 {
  margin-top: 8px;
}
</style>
